package org.jing.ext.windows;

import org.jing.core.lang.data.BaseDto;
import org.jing.core.lang.JingException;
import org.jing.core.logger.JingLogger;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * Description: <br>
 *
 * @author bks <br>
 * @since 2023-02-24 <br>
 */
public class Application extends BaseDto {
    private static final JingLogger LOGGER = JingLogger.getLogger(Application.class);

    private String appPath;

    private ArrayList<String> paramList = new ArrayList<>();

    public Application(String appPath) {
        this.appPath = appPath;
    }

    public Application(String appPath, String... params) {
        this.appPath = appPath;
        if (null != params) {
            paramList.addAll(Arrays.asList(params));
        }
    }

    public String getAppPath() {
        return appPath;
    }

    public void setAppPath(String appPath) {
        this.appPath = appPath;
    }

    public ArrayList<String> getParamList() {
        return paramList;
    }

    public void setParamList(ArrayList<String> paramList) {
        this.paramList = paramList;
    }

    public Application addParam(String param) {
        paramList.add(param);
        return this;
    }

    public boolean execute() {
        File appFile = new File(appPath);
        if (!appFile.exists() || !appFile.isFile()) {
            throw new JingException("application doesn't exist: {}", appPath);
        }
        StringBuilder stbr = new StringBuilder("\"" + appPath + "\"");
        for (String p$ : paramList) {
            stbr.append(" ").append(p$);
        }
        String cmd = stbr.toString();
        LOGGER.debug("execute: [{}]", cmd);
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            if (process.waitFor() == 0) {
                return true;
            }
        }
        catch (JingException e) {
            throw e;
        }
        catch (Throwable t) {
            throw new JingException(t);
        }
        return false;
    }

    public static void main(String[] args) {
        Application application = new Application("D:\\Program Files\\WinRAR\\WinRAR.exe");
        application.addParam("x").addParam("-o").addParam("-pfarmer")
            .addParam("D:\\WorkSpace\\idea\\jing-ext\\temp\\temp.zip.001")
            .addParam("D:\\WorkSpace\\idea\\jing-ext\\temp\\output");
        System.out.println(application.execute());
    }
}
